package com.WJY.controller;

import com.WJY.pojo.Student;
import com.WJY.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController   //声明是controller并返回方法本身
@RequestMapping("/MyStudent")   //web请求路径
@CrossOrigin  //解决跨域问题
public class StudentController {


    private R success(Object data) {
        return new R(200, data);
    }

    private R failure(String msg) {
        return new R(500, msg);
    }


    @Autowired
    private StudentService studentService;


    @GetMapping
    public R queryStudentList() {
        List<Student> list = studentService.queryStudentList();
        return list != null && !list.isEmpty() ? success(list) : failure("暂无学生");
    }

    @GetMapping("/{id}")
    public R queryStudentById(@PathVariable String id) {
        Student student = studentService.queryStudentById(Integer.parseInt(id));
        return student != null ? success(student) : failure("没有该学生");
    }

    @GetMapping(params = "name")
    public R queryStudentByName(String name) {
        List<Student> list = studentService.queryStudentByName(name);
        return list != null && !list.isEmpty() ? success(list) : failure("没有名字带" + name + "字的学生");
    }

    @DeleteMapping("/{id}")
    public R delStudentById(@PathVariable int id) {
        int i = studentService.delStudentById(id);
        return i > 0 ? success("删除成功") : failure("删除失败");
    }

    @PostMapping
    public R addStudent(@RequestBody Student student) {
        int i = studentService.addStudent(student);
        return i > 0 ? success("新增成功") : failure("新增失败");
    }

    @PutMapping
    public R updateStudent(@RequestBody Student student) {
        int i = studentService.updateStudent(student);
        return i > 0 ? success("更新成功") : failure("更新失败");
    }

}
